import { useState, useEffect } from 'react'
import { Capacitor } from '@capacitor/core'
import { App } from '@capacitor/app'
import { useAtomValue } from 'jotai'
import { autoOverlayOnBackgroundAtom, chatSessionSettingsAtom, settingsAtom } from '../../../stores/atoms/settingsAtoms'
import SystemOverlay from '../plugins/SystemOverlayPlugin'

export const useSystemOverlay = () => {
  const [hasPermission, setHasPermission] = useState(false)
  const [isSystemOverlayVisible, setIsSystemOverlayVisible] = useState(false)
  const [isCheckingPermission, setIsCheckingPermission] = useState(false)
  const isMobile = Capacitor.isNativePlatform()
  const autoOverlayOnBackground = useAtomValue(autoOverlayOnBackgroundAtom)
  // Session and global settings for building AI config
  const chatSessionSettings = useAtomValue(chatSessionSettingsAtom)
  const appSettings = useAtomValue(settingsAtom)
  const isPluginAvailable = () => {
    const platform = Capacitor.getPlatform()
    if (platform === 'android') return true
    return Capacitor.isPluginAvailable('SystemOverlay')
  }

  // 等待 Android 端原生插件桥接就绪，避免应用启动早期访问报错
  const waitForSystemOverlayReady = async (
    timeoutMs: number = 3000,
    intervalMs: number = 100
  ): Promise<boolean> => {
    // 使用 registerPlugin 后无需等待 window.Capacitor.Plugins 注入
    // Android 直接返回就绪，调用失败会在具体方法的 try/catch 中处理
    return true
  }

  // 检查权限
  const checkPermission = async () => {
    if (!isMobile) return false
    if (!isPluginAvailable()) {
      console.error('[SystemOverlay] plugin not available on this platform')
      alert('SystemOverlay 插件不可用。请在 Android 端运行 npx cap sync android（或 npm run mobile:sync:android）并保持 Capacitor 版本一致。')
      return false
    }
    const ready = await waitForSystemOverlayReady()
    if (!ready) {
      alert('SystemOverlay 原生插件尚未就绪，请稍后重试或重新打开应用。')
      return false
    }
    
    try {
      setIsCheckingPermission(true)
      const result = await SystemOverlay.checkOverlayPermission()
      console.log('权限检查结果:', result)
      setHasPermission(result.hasPermission)
      return result.hasPermission
    } catch (error) {
      console.error('检查悬浮窗权限失败:', error)
      alert('插件调用失败: ' + error)
      return false
    } finally {
      setIsCheckingPermission(false)
    }
  }

  // 请求权限
  const requestPermission = async () => {
    if (!isMobile) return false
    if (!isPluginAvailable()) {
      console.error('[SystemOverlay] plugin not available on this platform')
      alert('SystemOverlay 插件不可用。请先运行 npx cap sync android（或 npm run mobile:sync:android）并保持 Capacitor 版本一致。')
      return false
    }
    const ready = await waitForSystemOverlayReady()
    if (!ready) {
      alert('SystemOverlay 原生插件尚未就绪，请稍后重试或重新打开应用。')
      return false
    }
    
    try {
      const result = await SystemOverlay.requestOverlayPermission()
      if (result.granted) {
        setHasPermission(true)
      } else if ((result as any).message) {
        alert((result as any).message)
      }
      return result.granted
    } catch (error) {
      console.error('请求悬浮窗权限失败:', error)
      alert('无法打开权限设置页面，请手动在设置中允许悬浮窗权限')
      return false
    }
  }

  // 显示系统悬浮窗（当未传入 x/y 时，原生默认放置到右侧中间吸边）
  const showSystemOverlay = async (pos?: { x?: number; y?: number }) => {
    if (!isMobile || !hasPermission) return false
    if (!isPluginAvailable()) {
      console.error('[SystemOverlay] plugin not available on this platform')
      alert('SystemOverlay 插件不可用。请先运行 npx cap sync android（或 npm run mobile:sync:android）并保持 Capacitor 版本一致。')
      return false
    }
    const ready = await waitForSystemOverlayReady()
    if (!ready) return false
    
    try {
      const payload: { x?: number; y?: number; width?: number; height?: number } = {
        width: 56,
        height: 56,
        ...(pos ?? {})
      }
      await SystemOverlay.showSystemOverlay(payload)
      setIsSystemOverlayVisible(true)
      return true
    } catch (error) {
      console.error('显示系统悬浮窗失败:', error)
      return false
    }
  }

  // 隐藏系统悬浮窗
  const hideSystemOverlay = async () => {
    if (!isMobile) return
    if (!isPluginAvailable()) return
    const ready = await waitForSystemOverlayReady()
    if (!ready) return
    
    try {
      await SystemOverlay.hideSystemOverlay()
      setIsSystemOverlayVisible(false)
    } catch (error) {
      console.error('隐藏系统悬浮窗失败:', error)
    }
  }

  // 更新悬浮窗位置
  const updateOverlayPosition = async (x: number, y: number) => {
    if (!isMobile || !isSystemOverlayVisible) return
    if (!isPluginAvailable()) return
    const ready = await waitForSystemOverlayReady()
    if (!ready) return
    
    try {
      await SystemOverlay.updateOverlayPosition({ x, y })
    } catch (error) {
      console.error('更新悬浮窗位置失败:', error)
    }
  }

  // 监听悬浮窗移动事件（吸边后回调保存位置）。点击事件已在原生层处理为面板展开/收起，不再在前端监听。
  useEffect(() => {
    if (!isMobile) return
    if (!isPluginAvailable()) return

    const handleOverlayMoved = (data: { x?: number; y?: number }) => {
      try {
        const x = typeof data?.x === 'number' ? data.x : undefined
        const y = typeof data?.y === 'number' ? data.y : undefined
        if (typeof x === 'number' && typeof y === 'number') {
          localStorage.setItem('floating-button-position', JSON.stringify({ x, y }))
        }
      } catch {}
    }

    // 订阅原生事件
    const subMoved = SystemOverlay.addListener('overlayMoved', handleOverlayMoved)

    return () => {
      // 清理监听
      subMoved.then((h) => h.remove?.()).catch(() => {})
    }
  }, [isMobile])

  // Sync AI config to native overlay whenever session/provider settings change (Android only)
  useEffect(() => {
    if (!isMobile) return

    const pushAiConfig = async () => {
      try {
        // Ensure plugin readiness (no-op on Android with registerPlugin)
        const ready = await waitForSystemOverlayReady()
        if (!ready) return

        // Providers map from settings
        const providers = (appSettings?.providers ?? {}) as Record<string, any>

        // Derive provider/model with Gemini-first fallback
        const explicitProvider = (chatSessionSettings?.provider as string) || appSettings?.defaultChatModel?.provider
        let providerId = explicitProvider
        if (!providerId) {
          if ((providers as any)?.google?.apiKey) providerId = 'google'
          else if ((providers as any)?.gemini?.apiKey) providerId = 'gemini'
          else providerId = 'openai'
        }

        const explicitModel = chatSessionSettings?.modelId || appSettings?.defaultChatModel?.model
        let modelId = explicitModel as string | undefined
        if (!modelId) {
          modelId = (providerId === 'google' || providerId === 'gemini') ? 'gemini-1.5-flash' : 'gpt-4o-mini'
        }

        // Provider config (apiHost/apiPath/apiKey)
        const providerCfg = providers[providerId as string] || {}
        const apiPath = providerCfg?.apiPath as string | undefined

        // Ensure scheme for host if provided (avoid invalid URL in native)
        const ensureScheme = (h?: string) => {
          if (!h) return h
          const trimmed = h.trim()
          if (/^https?:\/\//i.test(trimmed)) return trimmed
          return `https://${trimmed}`
        }
        const apiKey = providerCfg?.apiKey as string | undefined

        // Build baseUrl
        let baseUrl: string | undefined
        if (providerId === 'google' || providerId === 'gemini') {
          // Respect configured host + path; native will avoid duplicating /v1beta if already present
          let apiHost = providerCfg?.apiHost as string | undefined
          apiHost = ensureScheme(apiHost)
          const trimRight = (s?: string) => (s ? s.replace(/\/+$/g, '') : '')
          const trimLeft = (s?: string) => (s ? s.replace(/^\/+/, '') : '')
          const joined = [trimRight(apiHost), trimLeft(apiPath)].filter(Boolean).join('/')
          baseUrl = joined || 'https://generativelanguage.googleapis.com'
        } else {
          // OpenAI-compatible providers
          let apiHost = providerCfg?.apiHost as string | undefined
          apiHost = ensureScheme(apiHost)
          const trimRight = (s?: string) => (s ? s.replace(/\/+$/g, '') : '')
          const trimLeft = (s?: string) => (s ? s.replace(/^\/+/, '') : '')
          const joined = [trimRight(apiHost), trimLeft(apiPath)].filter(Boolean).join('/')
          baseUrl = joined || undefined
        }

        // Temperature / topP from session with defaults
        const temperature = typeof chatSessionSettings?.temperature === 'number' ? chatSessionSettings.temperature : (typeof appSettings?.temperature === 'number' ? (appSettings as any).temperature : 0.7)
        const topP = typeof chatSessionSettings?.topP === 'number' ? chatSessionSettings.topP : (typeof appSettings?.topP === 'number' ? (appSettings as any).topP : 1.0)

        const cfg = {
          provider: providerId,
          model: modelId,
          apiKey: apiKey || '',
          ...(baseUrl ? { baseUrl } : {}),
          temperature,
          topP,
        }

        await SystemOverlay.setAiConfig({ configJson: JSON.stringify(cfg) })
      } catch (err) {
        // Silent fail; overlay will surface errors if invoked without config
        console.warn('[SystemOverlay] setAiConfig failed:', err)
      }
    }

    // Debounce slightly to avoid rapid successive writes
    const tid = setTimeout(() => {
      pushAiConfig()
    }, 50)
    return () => clearTimeout(tid)
  }, [isMobile, chatSessionSettings, appSettings])

  // 监听应用前后台切换，根据设置自动显示/隐藏系统悬浮窗
  useEffect(() => {
    if (!isMobile) return

    const sub = App.addListener('appStateChange', async ({ isActive }) => {
      if (isActive) {
        // 回到前台：隐藏系统悬浮窗，并重新检查权限（从设置返回等场景）
        try {
          await hideSystemOverlay()
        } catch {}
        checkPermission()
      } else {
        // 进入后台：若开启自动显示并已授权，则显示系统悬浮窗
        if (autoOverlayOnBackground) {
          let pos: { x?: number; y?: number } | undefined = undefined
          try {
            const saved = localStorage.getItem('floating-button-position')
            if (saved) {
              const parsed = JSON.parse(saved)
              if (typeof parsed?.x === 'number' && typeof parsed?.y === 'number') {
                pos = { x: parsed.x, y: parsed.y }
              }
            }
          } catch {}

          const permitted = await checkPermission()
          if (permitted && !isSystemOverlayVisible) {
            await showSystemOverlay(pos)
          }
        }
      }
    })

    return () => {
      sub.then((h) => h.remove()).catch(() => {})
    }
  }, [isMobile, autoOverlayOnBackground, isSystemOverlayVisible])

  // 初始化时检查权限
  useEffect(() => {
    // 调试：输出平台与插件信息
    try {
      const plugins = (window as any)?.Capacitor?.Plugins || {}
      console.log('[SystemOverlay][debug] platform=', Capacitor.getPlatform(), 'isNative=', Capacitor.isNativePlatform())
      console.log('[SystemOverlay][debug] registered plugins=', Object.keys(plugins))
      console.log('[SystemOverlay][debug] isPluginAvailable(SystemOverlay)=', Capacitor.isPluginAvailable?.('SystemOverlay'))
    } catch {}

    if (isMobile) {
      checkPermission()
    }
  }, [isMobile])

  return {
    hasPermission,
    isSystemOverlayVisible,
    isCheckingPermission,
    isMobile,
    checkPermission,
    requestPermission,
    showSystemOverlay,
    hideSystemOverlay,
    updateOverlayPosition
  }
}
